package com.yunyi.camunda.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.yunyi.camunda.mapper.IBusinessTaskMapper;
import com.yunyi.camunda.pojo.Result;
import com.yunyi.camunda.pojo.dto.BusinessTask;
import com.yunyi.camunda.pojo.dto.User;
import com.yunyi.camunda.pojo.vo.StartProcessRequest;
import com.yunyi.camunda.service.ProcessInstanceService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 操作工作流程service实现
 *
 * @author yunyi
 */
@Service
public class ProcessInstanceServiceImpl implements ProcessInstanceService {

    @Autowired
    private IBusinessTaskMapper businessTaskMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Override
    public Result<String> startProcessInstanceById(User user, StartProcessRequest request) {
        String processDefinitionId = request.getProcessDefinitionId();
        String businessKey = request.getBusinessKey();
        //前置的校验并不可少，比方说该条数据是否已经提交了一个流程，是否允许重复提交流程
        //查询业务数据
        //实际操作中并不需要查询所有的数据，只需要查询流程中需要的数据
        BusinessTask businessTask = businessTaskMapper.getBusinessTaskById(businessKey);
        if (businessTask == null) {
            return Result.failMessage("未查询到业务数据");
        }
        Map<String, Object> businessTaskMap = BeanUtil.beanToMap(businessTask);
        Map<String, Object> paramMap = new HashMap<>(16);
        //将业务数据传入参数
        paramMap.putAll(businessTaskMap);
        //为演示assignee的el表达式
        paramMap.put("preCheckUser1", "100001");
        paramMap.put("preCheckUser2", "100002");
        paramMap.put("preCheckUser3", "100003");
        //如果是使用key启动则使用startProcessInstanceByKey方法，参数是一样的
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId, request.getBusinessKey(), paramMap);
        //启动成功后还应该更改业务表中流程的字段，以标识是否启动该条业务数据的流程状态
        if (processInstance == null) {
            return Result.failMessage("启动失败");
        }
        return Result.success(processInstance.getProcessInstanceId());
    }
}
